package com.api.zszsj2.util;

import com.api.doc.detail.util.ooxml.commons.CommonUtils;
import com.api.doc.detail.util.ooxml.commons.Constant;
import com.api.doc.detail.util.ooxml.commons.DocUtils;
import com.engine.workflow.biz.requestForm.HtmlToPdfBiz;
import com.itextpdf.io.image.PngImageData;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.PngImage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import weaver.general.BaseBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;

public class cardTest {

    public static void test(){
        String baseFolderPath = DocUtils.temporaryDirectoryPath(Constant.CM_TEMP_FOLDER);

        String html = "";
        String cardBinary="";
        String qrBinary = "";
        encodeQR encoder = new encodeQR();

        int tt=0;
        while (tt<3){
            String cardHtml = "";
            String zcid = String.valueOf(Math.addExact(100,tt));
            String sybm = "部门-"+tt;
            String zcmc = "资产名称-"+tt;
            String zcbh = "AAABBBCCC-"+tt;
            String zclx = "测试资产";
            String ggxh = "规格-"+tt;
            String cfdd = "市府大楼-"+tt;
            String qdrq = "2023-09-0"+tt;
            String zclxbm = "[aaa-"+tt+"]";
            String zckpxsdwmc = "政数局下辖单位-"+tt;

            String uuid = CommonUtils.uuid();
            String htmlName = "zcCard_"+zcid+"_"+uuid;
            String qrName = "zcQr_"+zcid+"_"+uuid;
            String qrFilePath = baseFolderPath + File.separator +  qrName + ".png";
            String qrHtmlFilePath = baseFolderPath + File.separator +  qrName + ".html";
            encoder.encoderQRCoderToFile("https://xtbg.zs.gov.cn:88/api/assetCs/qr_card_info?zcid="+zcid,qrFilePath,0,160,0,0,null,"","/formmode/images/qrcodeError_wev8.png");
            qrBinary = "";
            qrBinary = imageFileToBinaryString(qrFilePath);

            /**
             * table样式
             */
            //font-family:Microsoft YaHei;//icon-workflo
            cardHtml += "<div style='display:block;width:298px;height:398px;padding:0;margin:0;font-size:12px;border: 1px solid #666;text-align:left;'>";
            cardHtml += "<table style='width:100%;height:100%;padding:0;margin:0;font-size:12px;'>";
            cardHtml += "<tbody align='left' width='100%' height='100%' style='text-align:left'>";
            cardHtml += "<tr><td colspan='2' width='100%' height='30' align='center' style='padding:0 12px;font-size:14px;font-weight:600;text-align: center;'>"+(zckpxsdwmc.isEmpty()?sybm:zckpxsdwmc)+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>资产名称：</td><td align='left' style='text-align:left;padding-right:12px'>"+zcmc+zcmc+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>资产编号：</td><td align='left' style='text-align:left;padding-right:12px'>"+zcbh+zcbh+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>资产类型：</td><td align='left' style='text-align:left;padding-right:12px'>["+zclxbm+"]"+zclx+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>规格型号：</td><td align='left' style='text-align:left;padding-right:12px'>"+ggxh+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>存放地点：</td><td align='left' style='text-align:left;padding-right:12px'>"+cfdd+"</td></tr>";
            cardHtml += "<tr><td height='30' align='left' style='padding-left:12px;'>取得日期：</td><td align='left' style='text-align:left;padding-right:12px'>"+qdrq+"</td></tr>";
            String cardHtml2 = cardHtml;

            cardHtml += "<tr><td colspan='2' width='100%' align='center' style='min-height:160px;text-align: center;'><img src='data:image/png;base64,"+qrBinary+"' style='width:160px'></img></td></tr>";

            cardHtml += "</tbody>";
            cardHtml2 += "</tbody>";
            cardHtml += "</table>";
            cardHtml2 += "</table>";
            cardHtml += "</div>";
            cardHtml2 += "</div>";
            html += "<div>"+cardHtml+"</div>";//test show

            ArrayList infos = new ArrayList();
            String[] kv = new String[2];
            kv[0] = "资产名称"; kv[1] = zcmc; infos.add(kv);
            String[] kv2 = new String[2];
            kv2[0] = "资产编号"; kv2[1] = zcbh; infos.add(kv2);
            String[] kv3 = new String[2];
            kv3[0] = "资产类型"; kv3[1] = zclx; infos.add(kv3);
            String[] kv4 = new String[2];
            kv4[0] = "规格型号"; kv4[1] = ggxh; infos.add(kv4);
            String[] kv5 = new String[2];
            kv5[0] = "存放地点"; kv5[1] = cfdd; infos.add(kv5);
            String[] kv6 = new String[2];
            kv6[0] = "取得日期"; kv6[1] = qdrq; infos.add(kv6);


            String htmlPngPath = baseFolderPath + File.separator + htmlName + ".png";
            String htmlFileName = baseFolderPath + File.separator + htmlName ;
            cardBinary="";
            try {
                try {
                    tableToPdf(zckpxsdwmc.isEmpty()?sybm:zckpxsdwmc, infos, qrFilePath, htmlFileName);
                    cardBinary = imageFileToBinaryString(htmlPngPath);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            html += "<div><img src='data:image/jpg;base64,"+cardBinary+"' /></div>";
            tt++;
        }
    };

    public static void tableToPdf(String sybm, ArrayList infos, String qrFileName, String htmlPath) throws Exception{
        //todo see: https://blog.csdn.net/double_hll123/article/details/127421837
        BaseBean baseBean = new BaseBean();
        String pdfFile = htmlPath+".pdf";
        String htmlFlie = htmlPath+".html";

        FileOutputStream fos = new FileOutputStream(pdfFile);
        Document doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc,fos);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
        Rectangle rectangle = new Rectangle(300,400);
        writer.setPageSize(rectangle);
        doc.open();

        float[] colWidths = {70,230};

        PdfPTable table = new PdfPTable(colWidths);
        table.setTotalWidth(310);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);

        //部门名称 行
        PdfPCell pCell = new PdfPCell();
        pCell.setColspan(2);
        _setTableStyle(table,pCell,Element.ALIGN_CENTER);
        Paragraph paragraph = new Paragraph(sybm,getPdfChineseFont(14,1));
        pCell.setPhrase(paragraph);
        table.addCell(pCell);
        //内容行
        for(int i=0; i<infos.size(); i++){
            String[] info = (String[]) infos.get(i);
            for (int s=0; s<2; s++){
                pCell = new PdfPCell();
                _setTableStyle(table,pCell,Element.ALIGN_LEFT);
                paragraph = new Paragraph(info[s],getPdfChineseFont(12,0));
                pCell.setPhrase(paragraph);
                table.addCell(pCell);
            }
        }
        //二维码
        pCell = new PdfPCell();
        pCell.setColspan(2);
        _setTableStyle(table,pCell,Element.ALIGN_CENTER);
        _addImageToCell(pCell,qrFileName);
        table.addCell(pCell);

        doc.add(table);
        doc.close();
    }

    private static void _setTableStyle(PdfPTable table,PdfPCell cell, int align){
        table.setLockedWidth(true);
        table.setTotalWidth(300);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell.setFixedHeight(28);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);//垂直对齐方式
        if(align>0){
            cell.setHorizontalAlignment(align);//水平对齐方式
        }else{
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);//水平对齐方式
        }
        cell.setBackgroundColor(BaseColor.WHITE);
        cell.setBorder(1);
        cell.setBorderWidth(1);
        cell.setBorderWidthTop(1);
        cell.setBorderWidthBottom(1);
        cell.setBorderWidthLeft(1);
        cell.setBorderWidthRight(1);
        cell.setBorderColor(BaseColor.BLACK);
        cell.setPadding(0);
    }
    private static Font getPdfChineseFont(Integer fontSize, Integer isBlod) throws Exception{
        if(fontSize == null)
            fontSize = 12;
        String configpath = "/font/workflow";
        String rootpath = HtmlToPdfBiz.getSystemDir();
        String fontsPath = rootpath + configpath;

        BaseFont bsFont = BaseFont.createFont(fontsPath+"/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bsFont, 12, isBlod);
        fontChinese.setColor(BaseColor.BLACK);
        fontChinese.setSize(fontSize);
        return fontChinese;
    }
    private static void _addImageToCell(PdfPCell cell, String imagePath) throws Exception{
        File file = new File(imagePath);  // 图片文件路径
        try {
//            FileInputStream fis = new FileInputStream(file);  // 创建输入流
//            // 步骤2：将图片数据转换为字节数组
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int len;
//            while ((len = fis.read(buffer)) != -1) {
//                bos.write(buffer, 0, len);
//            }
//            byte[] imageData = bos.toByteArray();
            Image jpg = PngImage.getImage(imagePath);
            cell.setImage(jpg);
            cell.setFixedHeight(150);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String imageFileToBinaryString(String filwPath){
        // 步骤1：读取图片文件
        File file = new File(filwPath);  // 图片文件路径
        try {
            FileInputStream fis = new FileInputStream(file);  // 创建输入流
            // 步骤2：将图片数据转换为字节数组
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            byte[] imageData = bos.toByteArray();

            // 步骤3：将字节数组转换为二进制字符串
            String binaryString = Base64.getEncoder().encodeToString(imageData);
            return binaryString;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public void PDFToImageConverter(String fromPath,String toPath) throws IOException{
        PDDocument pdf = null;
        BaseBean baseBean = new BaseBean();
        try{
            pdf = PDDocument.load(new File(fromPath));
            PDFRenderer render = new PDFRenderer(pdf);
            for (int pageIndex=0; pageIndex<pdf.getNumberOfPages(); pageIndex++){
                BufferedImage image = render.renderImage(pageIndex,1.333f);
//
//                BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
//                Graphics2D g = newImage.createGraphics();
//                render.renderPageToGraphics(pageIndex,g);
//                ImageIO.write(newImage,"png", new File(toPath+".png"));

                baseBean.writeLog("PDFToImageConverter ：getWidth=" + image.getWidth()+", getHeight=" + image.getHeight());
                BufferedImage cut_image = image.getSubimage(0,0,300,400);
                if(toPath.isEmpty() && fromPath.indexOf(".pdf")>fromPath.length()-3){
                    toPath = fromPath.substring(0,fromPath.length()-4);
                }
                ImageIO.write(cut_image,"png", new File(toPath+".png"));
//                ImageIO.write(image,"png", new File(toPath+".png"));
            }
        }finally {
            if(pdf!=null)
                pdf.close();
        }
    }
}